<template>
  <div class="app-container">
    <br>
    <el-tabs v-model="editableTabsValue" type="border-card" closable @tab-remove="removeTab">
      
      <el-tab-pane
        label="挂号列表"
        name="挂号列表"
      >
        <el-table
          v-loading="listLoading"
          :data="list"
          element-loading-text="Loading"
          border
          fit
          highlight-current-row
          :row-class-name="tableRowClassName"
        > 
          <el-table-column align="center" label="序号" width="50">
            <template slot-scope="scope">
              {{ scope.$index + 1 }}
            </template>
          </el-table-column>
          <el-table-column label="会员编号" width="120" align="center">
            <template slot-scope="scope">
              {{ scope.row.patientCode }}
            </template>
          </el-table-column>
          <el-table-column label="姓名" width="100" align="center">
            <template slot-scope="scope">
              {{ scope.row.patientName }}
            </template>
          </el-table-column>
          <el-table-column label="等级" width="60" align="center">
            <template slot-scope="scope">
              {{ scope.row.vipLevel }}
            </template>
          </el-table-column>
          <el-table-column label="就诊方式" width="100" align="center">
            <template slot-scope="scope">
              {{ scope.row.typeName }}
            </template>
          </el-table-column>
          <el-table-column label="就诊医生" width="120" align="center">
            <template #header >
              <el-badge :hidden="noMasterDoctorNum==0" :value="noMasterDoctorNum" class="item">
                <div style="width: 100%;">
                  <span>就诊医生</span><br>
                </div>
              </el-badge>
            </template>
            <template slot-scope="scope">
              {{ scope.row.doctorName }}
            </template>
          </el-table-column> 
           <el-table-column label="就诊科室" width="100" align="center">
            <template slot-scope="scope">
              {{ scope.row.jobOfficeName }}
            </template>
          </el-table-column>
          <el-table-column label="就诊诊室" width="100" align="center">
            <template slot-scope="scope">
              {{ scope.row.workAddressName }}
            </template>
          </el-table-column>
          <el-table-column label="就诊类型" width="100" align="center">
            <template slot-scope="scope">
              {{ scope.row.visitType }}
            </template>
          </el-table-column>
          <el-table-column :label="'诊前静息\n剩余时间'" width="100" align="center">
            <template #header >
              <el-badge :value="doneWaitingNum" class="item">
                <div style="width: 100%;">
                  <span>{{ '诊前静息' }}</span><br>
                  <span>{{ '剩余时间' }}</span>
                </div>
              </el-badge>
            </template>
            <template slot-scope="scope">
              {{ scope.row.remainderTime }}
            </template>
          </el-table-column>
          <el-table-column :label="'挂号后\n时长'" width="80" align="center">
            <template slot-scope="scope">
              {{ scope.row.afterGuidanceTime }}
            </template>
          </el-table-column>
          <!-- <el-table-column label="挂号费(元)" width="150" align="center">
            <template slot-scope="scope">
              {{ scope.row.registerPrice }}
            </template>
          </el-table-column> -->
          <el-table-column :label="'诊前实验室\n检查'" width="110" align="center">
            <template #header >
              <el-badge :value="noInspectionNum" class="item">
                <div style="width: 100%;">
                  <span>{{'诊前实验室'}}</span><br>
                  <span>{{ '检查' }}</span>
                </div>
              </el-badge>
            </template>
            <template slot-scope="scope">
              {{ scope.row.remainderTime }}
            </template>
          </el-table-column>
          <el-table-column :label="'诊前诊室\n检查'" width="100" align="center">
            <template #header >
              <el-badge :value="noCheckNum" class="item">
                <div style="width: 100%;">
                  <span>{{ '诊前诊室' }}</span><br>
                  <span>{{ '检查' }}</span>
                </div>
              </el-badge>
            </template>
            <template slot-scope="scope">
              {{ scope.row.remainderTime }}
            </template>
          </el-table-column>
          <el-table-column :label="'诊前信息\n采集'" width="100" align="center">
            <template #header >
              <el-badge :value="noInfoNum" class="item">
                <div style="width: 100%;">
                  <span>{{ '诊前信息' }}</span><br>
                  <span> {{ '采集' }} </span>
                </div>
              </el-badge>
            </template>
            <template slot-scope="scope">
              {{ scope.row.remainderTime }}
            </template>
          </el-table-column>
          <el-table-column label="就诊状态" width="80" align="center">
            <template slot-scope="scope">
              <el-tag :type="scope.row.status | statusColorFilter">{{ scope.row.status | statusFilter }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column class-name="status-col" label="操作" align="center" width="150" >
            <template slot-scope="scope">
              <el-button type="primary" @click="optionGuidance(scope.row)">诊前操作</el-button>
            </template>
          </el-table-column>
        </el-table>
        <el-pagination
          background
          layout="->, total, prev, pager, next"
          :total="this.total"
          :current-page="currentPage"
          :page-size="pageSize"
          @current-change="clickCurPage"
          >
        </el-pagination>
      </el-tab-pane>

      <el-tab-pane
        v-for="item in editableTabs"
        :key="item.name"
        :label="item.title"
        :name="item.name"
      >

        <!-- patient detail -->
        <div >
          <el-container>
            <el-main>
              <el-row :gutter=10>
                  <el-col :span=4><span style="font-size: 16px;">就诊状态: 诊前/排队中</span></el-col>
                  <el-col :span=12>
                    <span class="main-head-title">实验室检查开立 未完成 / </span>
                    <span class="main-head-title">诊室检查开立 未完成 / </span>
                    <span class="main-head-title">诊前信息采集 未完成 / </span>
                  </el-col>
              </el-row>
              <br>
              <el-collapse >
                <el-collapse-item name="1">
                  <template slot="title">
                    <el-row :gutter=10>
                      <el-col :span=24>
                        <span class="main-head-title">基础信息: </span>
                        <span class="main-head-title">
                          {{item.content.code + ' '}}
                          {{item.content.name + ' '}}
                          {{item.content.sex + ' '}}
                          {{item.content.age + '周岁 /'}}
                          {{'手机尾号:'+ item.content.phone + ' /'}}
                          {{'身份证号:'+ item.content.idCard + ' /'}}
                          {{'出生日期:'+ item.content.birthday + ' '}}{{item.content.birthdayType | birthdayTypeFilter}}{{' /'}}
                          {{'会员等级:'}}{{item.content.vipLevel?item.content.vipLevel:'V0' }}
                        </span>
                      </el-col>
                    </el-row>
                  </template>
                    <el-row :gutter=10>
                      <el-col :span=24>
                        <span class="main-head-title">就诊信息: </span>
                        <span class="main-head-title">
                          就诊信息内容
                        </span>
                        </el-col>
                    </el-row>
                    <el-row :gutter=10>
                      <el-col :span=24>
                        <span class="main-head-title">卡券信息: </span>
                        <span class="main-head-title">卡券信息内容 </span>
                      </el-col>
                    </el-row>
                    <el-row :gutter=10>
                      <el-col :span=24>
                        <span class="main-head-title">用药信息: </span>
                        <span class="main-head-title">用药信息内容 </span>
                      </el-col>
                    </el-row>
                    <el-row :gutter=10>
                      <el-col :span=24>
                        <span class="main-head-title">预案信息: </span>
                        <span class="main-head-title">预案信息内容</span>
                      </el-col>
                    </el-row>
                    <el-row :gutter=10>
                      <el-col :span=24>
                        <span class="main-head-title">诊断信息: </span>
                        <span class="main-head-title">诊断信息内容</span>
                      </el-col>
                    </el-row>
                    <el-row :gutter=10>
                      <el-col :span=24>
                        <span class="main-head-title">就诊习惯: </span>
                        <span class="main-head-title">就诊习惯内容</span>
                      </el-col>
                    </el-row>
                </el-collapse-item>
              </el-collapse>
              
              <el-tabs v-model="item.content.patientTabsValue" type="border-card" closable @tab-remove="(targetName) => removePatientTab(targetName, item.content)">
                <el-tab-pane
                  v-for="patientTab in item.content.patientTabs"
                  :key="patientTab.name"
                  :label="patientTab.title"
                  :name="patientTab.name"
                >

                <div v-if="item.content.patientTabsValue == '会员管理'">
                  <el-form :model="item.content" label-width="120px" :rules="addPatientFormRules">
                    <el-row :gutter="10">
                      <!-- <el-col :span=8 >
                        <el-form-item label="编号">
                          <el-input v-model="addPatientForm.code" />
                        </el-form-item>
                      </el-col> -->
                      <el-col :span=8 >
                        <el-form-item label="姓名" prop="name">
                          <el-input v-model="item.content.name" :disabled="true" />
                        </el-form-item>
                      </el-col>
                      <el-col :span=6 >
                        <el-form-item label="性别" prop="sex">
                          <el-select v-model="item.content.sex" placeholder="请选择" :disabled="true" >
                            <el-option
                              v-for="item in sexEnum"
                              :key="item"
                              :label="item"
                              :value="item">
                            </el-option>
                          </el-select>
                        </el-form-item>
                      </el-col>
                    </el-row>
                    <el-row :gutter="10">
                      <el-col :span=6 >
                        <el-form-item label="手机号1" prop="phone">
                          <el-input v-model="item.content.phone" @input="inputPhone" maxlength="11" :disabled="true" />
                        </el-form-item>
                      </el-col>
                      <el-col :span=6 >
                        <el-form-item label="手机号2" >
                          <el-input v-model="item.content.phoneTwo" @input="inputPhone" maxlength="11" :disabled="true" />
                        </el-form-item>
                      </el-col>
                      <el-col :span=6 >
                        <el-form-item label="手机号3" >
                          <el-input v-model="item.content.phoneThree" @input="inputPhone" maxlength="11" :disabled="true" />
                        </el-form-item>
                      </el-col>
                      <el-col :span=6 >
                        <el-form-item label="身份证号" prop="idCard">
                          <el-input style="width: 100%" v-model="item.content.idCard" @input="inputIdCard" maxlength="18" :disabled="true" />
                        </el-form-item>
                      </el-col>
                    </el-row>
                    <el-row :gutter="10">
                      <el-col :span=4 >
                        <el-form-item label="出生日期" prop="birthday">
                          <el-date-picker v-model="item.content.birthday" type="date" placeholder="选择日期" value-format="yyyy-MM-dd" @change="changeBirthday" :disabled="true" ></el-date-picker>
                        </el-form-item>
                      </el-col>
                      <el-col :span=6 :offset=4>
                        <el-form-item label="农历/公历" prop="birthdayType">
                          <el-select v-model="item.content.birthdayType" placeholder="请选择" :disabled="true" >
                            <el-option
                              v-for="item in birthdayTypeEnum"
                              :key="item.id"
                              :label="item.name"
                              :value="item.id">
                            </el-option>
                          </el-select>
                        </el-form-item>
                      </el-col>
                      <el-col :span=6 >
                        <el-form-item label="年龄">
                          <el-input v-model="item.content.age" type="Number" min=0  :disabled="true" />
                        </el-form-item>
                      </el-col>
                    </el-row>
                    <el-row :gutter="10">
                      <el-col :span=8 >
                        <el-form-item label="来源" prop="source">
                          <el-select v-model="item.content.source" placeholder="请选择" :disabled="true" >
                            <el-option
                              v-for="item in sourceEnum"
                              :key="item.id"
                              :label="item.source"
                              :value="item.id"
                              >
                            </el-option>
                          </el-select>
                        </el-form-item>
                      </el-col>
                      <el-col :span=8 >
                        <el-form-item label="介绍人" v-if="item.content.source == 1 || item.content.source == 2" >
                          <el-select v-if="item.content.source == 1" v-model="item.content.introducer" placeholder="请选择" :disabled="true">
                            <el-option
                              v-for="item in patientEnum"
                              :key="item.id"
                              :label="item.code + ' - ' +item.name"
                              :value="item.id">
                            </el-option>
                          </el-select>
                          <el-select v-else-if="item.content.source == 2" v-model="item.content.introducer" placeholder="请选择" :disabled="true">
                            <el-option
                              v-for="item in userEnum"
                              :key="item.id"
                              :label="item.jobNumber + ' - ' + item.name"
                              :value="item.id">
                            </el-option>
                          </el-select>
                        </el-form-item>
                      </el-col>
                    </el-row>
                    <div style="width:100%;border: 2px solid #E4E7ED;padding: 10px;">
                      <div v-for="(address, index) in item.content.addressList" :key="index" >
                        <el-row :gutter="10" v-if="index != 0">
                          <el-col :span=6>
                            <el-form-item label="多址说明" prop="multiAddressDes">
                              <el-select v-model="address.multiAddressDes" placeholder="请选择" :disabled="true" >
                                <el-option
                                  v-for="item in multiAddressDesEnum"
                                  :key="item"
                                  :label="item"
                                  :value="item"
                                >
                                </el-option>
                              </el-select>
                            </el-form-item>
                          </el-col>
                          <el-col :span=6>
                            <el-form-item label="说明填写" v-if="address.isOtherAddress == 1" prop="multiAddressDesOther">
                              <el-input v-model="address.multiAddressDesOther" :disabled="true"/>
                            </el-form-item>
                          </el-col>
                        </el-row>
                        <el-row :gutter="10">
                          <el-col :span=8 >
                            <el-form-item label="省/市/区" prop="addressPre" >
                              <el-cascader
                                :disabled="true"
                                size="large"
                                :options="options"
                                v-model="address.addressPre"
                                :props="{ value: 'label', label: 'label'}"
                                >
                              </el-cascader>
                            </el-form-item>
                          </el-col>
                          <el-col :span=6>
                            <el-form-item label="小区" prop="addressMid">
                              <el-input v-model="address.addressMid" :disabled="true" ></el-input>
                            </el-form-item>
                          </el-col>
                          <el-col :span=10 >
                            <el-form-item label="详细地址" prop="addressInfo">
                              <el-input v-model="address.addressInfo" :disabled="true" ></el-input>
                            </el-form-item>
                          </el-col>
                        </el-row>
                        <el-row :gutter="10">
                          <el-col :span=8 >
                            <el-form-item label="距离" prop="retailStore">
                              <el-select v-model="address.retailStore" placeholder="门店请选择" :disabled="true" >
                                <el-option
                                  v-for="item in deptEnum"
                                  :key="item"
                                  :label="item"
                                  :value="item"
                                >
                                </el-option>
                              </el-select>
                            </el-form-item>
                          </el-col>
                          <el-col :span=8 >
                            <el-form-item label="公交站数" prop="distance">
                              <el-input v-model="address.distance" type="Number" min=0 :disabled="true" />
                            </el-form-item>
                          </el-col>
                        </el-row>
                        <el-divider></el-divider>
                      </div>
                    </div>
                  </el-form>
                </div>

                <div v-if="item.content.patientTabsValue == '诊前处置'">
                  <el-container>
                    <el-aside width="70%">
                      <div style="width: 100%;text-align: left;">
                        <span class="main-head-title">实验室检查开立 未完成 / </span>
                        <span class="main-head-title">诊室检查开立 未完成 / </span>
                        <span class="main-head-title">诊前信息采集 未完成 / </span>
                      </div>
                    </el-aside>
                    <el-main>
                      <div style="width: 100%;height: 100%;text-align: left;padding: 5px;">
                        <el-button type="primary" @click="stopVisit(item.content)" :disabled="item.content.guidanceInfo.status == 5 || item.content.guidanceInfo.status == 6">停止服务</el-button>
                      </div>
                    </el-main>
                  </el-container>

                  <el-collapse v-model="item.content.visitActiveName" accordion>
                    <el-collapse-item title="诊前·实验室检查开立" name="诊前·实验室检查开立">
                      <div>
                        <span>上次检查日期 ?</span>
                        <div class="body-item-contents">
                          <!-- <span style="dispaly: inline-block;margin: 5px;">分装商品总价: {{ form.subPackagePlanTotalAmount }}</span> -->
                          <el-autocomplete
                            value-key="pinyinCode"
                            class="inline-input"
                            v-model="item.content.inspectionSearchValue"
                            :fetch-suggestions="queryInspectionSearch"
                            placeholder="请输入 拼音简码"
                            :trigger-on-focus="false"
                            @select="(check) => {handleInspectionSelect(check, 3, item.content)}"
                            style="width: 100%;"
                          >
                            <template slot-scope="{ item }">
                              <span >{{ item.name? item.name+'/' : '' }}</span>
                              <span >{{ item.commonName? item.commonName+' ' : '' }}</span>
                              <span >{{ item.form? item.form+' ' : '' }}</span>
                              <span >{{ item.specs? item.specs+' ' : ''  }}</span>
                              <span >{{ item.factory? item.factory+' ' : '' }}</span>
                              <span >{{ item.productTime ? '(' + item.productTime.split('T')[0] + '—' + item.expiration.split('T')[0] + ')' : '' }}</span>
                            </template>
                          </el-autocomplete>
                          <el-table
                            style="width: 100%;white-space: pre-wrap;"
                            :data="item.content.visitInspectionList"
                            element-loading-text="Loading"
                            border
                            fit
                          > 
                            <el-table-column label="序号" align="center" width="40">
                              <template slot-scope="subDrugScope">
                                {{ subDrugScope.$index+1 }}
                              </template>
                            </el-table-column>
                            <el-table-column :label="'商品编码'" width="100" align="center" prop="code"></el-table-column>
                            <el-table-column :label="'实验室检测\n商品\n名称'" align="center" width="100">
                              <template slot-scope="subDrugScope">
                                <span>{{ '[' +subDrugScope.row.commonName + ']' }}</span><br>
                                <span>{{ subDrugScope.row.name }}</span><br>
                                <span>{{ subDrugScope.row.specs }}</span>
                              </template>
                            </el-table-column>
                            <el-table-column :label="'结果查\n询时长'" align="center" width="70" >
                              <template slot-scope="subDrugScope">
                                {{ subDrugScope.row.resultTime == '小时' ? subDrugScope.row.timeNumber + '小时' : subDrugScope.row.resultTime }}
                              </template>
                            </el-table-column>
                            <el-table-column :label="'单价'" align="center" width="70" >
                              <template slot-scope="subDrugScope">
                                {{ subDrugScope.row.unitPrice + '/' + subDrugScope.row.outerUnit }}
                              </template>
                            </el-table-column>
                            <el-table-column label="处方/药房操作" align="center" >
                              <el-table-column label="数量" align="center" width="140">
                                <template slot-scope="subDrugScope">
                                  <el-input type="Number" min=1 placeholder="请输入" v-model="subDrugScope.row.realQuantity" @input="inputRealQuantity(item.content)">
                                    <template slot="append">
                                      <span style="font-size: 14px">{{ subDrugScope.row.outerUnit }}</span>
                                    </template>
                                  </el-input>
                                </template>
                              </el-table-column>
                              <el-table-column :label="'单品\n金额'" align="center" width="70">
                                <template slot-scope="subDrugScope">
                                  {{ subDrugScope.row.totalPrice1 }}
                                </template>
                              </el-table-column>
                              <el-table-column :label="'储值卡\n单价'" align="center" width="70">
                                <template slot-scope="subDrugScope">
                                  {{ subDrugScope.row.totalPrice2 }}
                                </template>
                              </el-table-column>
                              <el-table-column :label="'操作'" align="center" width="120">
                                <template slot-scope="subDrugScope">
                                  <el-radio-group :value="subDrugScope.row.operation" style="display: flex;flex-direction: column;text-align: left;" @input="(value) => selectoperation(value, subDrugScope.row)">
                                    <el-radio :label="1" >选择操作</el-radio>
                                    <el-radio :label="2" >不选择操作</el-radio>
                                    <el-radio :label="3" >缴费预存</el-radio>
                                  </el-radio-group><br>
                                  <div v-if="subDrugScope.row.operation == 2 && subDrugScope.row.operationMark" ><span style="font-size: 12px;color: red;">不操作原因:{{ subDrugScope.row.operationMark }}</span></div>
                                </template>
                              </el-table-column>
                              <el-table-column label="使用节点" align="center" width="100">
                                <template slot-scope="subDrugScope">
                                  <el-radio-group v-model="subDrugScope.row.operationStep" style="display: flex;flex-direction: column;text-align: left;">
                                    <el-radio :label="1">诊中</el-radio>
                                    <el-radio :label="2">诊后</el-radio>
                                  </el-radio-group>
                                </template>
                              </el-table-column>
                              <el-table-column label="来源" align="center" width="100">
                                <template slot-scope="subDrugScope">
                                  {{ subDrugScope.row.source }}
                                  <!-- <el-input type="textarea" v-model="subDrugScope.row.source" ></el-input> -->
                                </template>
                              </el-table-column>
                              <el-table-column label="上次检查时间" align="center" width="100">
                                <template slot-scope="subDrugScope">
                                  {{ subDrugScope.row.lastTime }}
                                </template>
                              </el-table-column>
                              <el-table-column label="活动" align="center" width="200">

                              </el-table-column>
                            </el-table-column>
                          </el-table>

                          <el-divider content-position="left">按处方/药房取药计算</el-divider>
                          <el-table
                            style="width: 100%;white-space: pre-wrap;"
                            :data="item.content.visitInspectionRealReport"
                            element-loading-text="Loading"
                            border
                            fit
                            :show-header="false"
                          > 
                            <el-table-column label="处方金额" align="center" width="80">
                              <template slot-scope="subDrugReportsScope">
                                {{ subDrugReportsScope.row.PLAN_AMOUNT }} <br>
                              </template>
                            </el-table-column>
                            <el-table-column label="" align="center" width="80">
                              <template slot-scope="subDrugReportsScope">
                                {{ subDrugReportsScope.row.planAmount }} <br>
                              </template>
                            </el-table-column>
                            <el-table-column label="储值卡处方金额" align="center" width="120">
                              <template slot-scope="subDrugReportsScope">
                                {{ subDrugReportsScope.row.CARD_PLAN_AMOUNT }} <br>
                              </template>
                            </el-table-column>
                            <el-table-column label="" align="center" width="80">
                              <template slot-scope="subDrugReportsScope">
                                {{ subDrugReportsScope.row.cardPlanAmount }} <br>
                              </template>
                            </el-table-column>
                            <el-table-column label="活动处方金额" align="center" width="120">
                              <template slot-scope="subDrugReportsScope">
                                {{ subDrugReportsScope.row.ACTIVITY_PLAN_AMOUNT }} <br>
                              </template>
                            </el-table-column>
                            <el-table-column label="" align="center" width="80">
                              <template slot-scope="subDrugReportsScope">
                                {{ subDrugReportsScope.row.activityPlanAmount }} <br>
                              </template>
                            </el-table-column>
                            <el-table-column :label="'活动+储值卡金额'" align="center" width="140">
                              <template slot-scope="subDrugReportsScope">
                                {{ subDrugReportsScope.row.ACTIVITY_CARD_PLAN_AMOUNT }} <br>
                              </template>
                            </el-table-column>
                            <el-table-column label="" align="center" width="80">
                              <template slot-scope="subDrugReportsScope">
                                {{ subDrugReportsScope.row.activityCardPlanAmount }} <br>
                              </template>
                            </el-table-column>
                          </el-table>
                        </div>
                      </div>
                      <div style="display: flex;flex-direction: row;justify-content: end;margin: 5px;">
                        <el-button type="primary" @click="confirmVisit(item.content, 1)" :disabled="item.content.guidanceInfo.status == 5 || item.content.guidanceInfo.status == 6">实验室检查提交</el-button>
                      </div>
                    </el-collapse-item>
                    <el-collapse-item title="诊前·诊室检查开立" name="诊前·诊室检查开立">
                      <el-tabs type="border-card">
                        <el-tab-pane
                          v-for="checkTemplateTab in item.content.checkTemplate"
                          :key="checkTemplateTab.templateName"
                          :label="checkTemplateTab.templateName"
                          :name="checkTemplateTab.templateName"
                        >
                        <el-form ref="addPatientForm" :model="addPatientForm" label-width="120px" :rules="addPatientFormRules">
                          <el-form-item v-for="(checkItem, index) in checkTemplateTab.templateContent" :key="index" :label="checkItem.name" >
                            <el-input v-model="checkItem.value"></el-input>
                          </el-form-item>
                          <div style="display: flex;flex-direction: row;justify-content: end;margin: 5px;">
                            <el-button type="primary" @click="confirmVisit(item.content, 2)" :disabled="item.content.guidanceInfo.status == 5 || item.content.guidanceInfo.status == 6">诊室检查提交</el-button>
                          </div>
                        </el-form>
                        </el-tab-pane>
                      </el-tabs>
                      
                    </el-collapse-item>
                    <el-collapse-item title="诊前·信息采集" name="诊前·信息采集">
                      <div>信息采集内容</div>
                      <div style="display: flex;flex-direction: row;justify-content: end;margin: 5px;">
                        <el-button type="primary" @click="confirmVisit(item.content, 3)" :disabled="item.content.guidanceInfo.status == 5 || item.content.guidanceInfo.status == 6">信息采集提交</el-button>
                      </div>
                    </el-collapse-item>
                  </el-collapse>

                </div>

                <div v-if="item.content.patientTabsValue == '会员就诊记录查询'">
                  会员就诊记录查询内容
                </div>

                <div v-if="item.content.patientTabsValue == '邮寄信息添加/修改'">
                  <el-form ref="addPatientForm" :model="addPatientForm" label-width="120px" :rules="addPatientFormRules">
                    <div style="width:100%;border: 2px solid #E4E7ED;padding: 10px;">
                      <div v-for="(address, index) in item.content.addressList" :key="index" >
                        <el-button type="danger" icon="el-icon-delete" circle @click="deleteAddress(address, item.content.addressList)"></el-button>
                        <el-row :gutter="10" v-if="index != 0">
                          <el-col :span=6>
                            <el-form-item label="多址说明" prop="multiAddressDes">
                              <el-select v-model="address.multiAddressDes" placeholder="请选择" >
                                <el-option
                                  v-for="item in multiAddressDesEnum"
                                  :key="item"
                                  :label="item"
                                  :value="item"
                                  @click.native="changeMultiAddressDes(item, address)"
                                >
                                </el-option>
                              </el-select>
                            </el-form-item>
                          </el-col>
                          <el-col :span=6>
                            <el-form-item label="说明填写" v-if="address.isOtherAddress == 1" prop="multiAddressDesOther">
                              <el-input v-model="address.multiAddressDesOther"/>
                            </el-form-item>
                          </el-col>
                        </el-row>
                        <el-row :gutter="10">
                          <el-col :span=8 >
                            <el-form-item label="省/市/区" prop="addressPre">
                              <el-cascader
                                size="large"
                                :options="options"
                                v-model="address.addressPre"
                                @change="handleChange"
                                :props="{ value: 'label', label: 'label'}"
                              >
                              </el-cascader>
                            </el-form-item>
                          </el-col>
                          <el-col :span=6>
                            <el-form-item label="小区" prop="addressMid">
                              <el-input v-model="address.addressMid"></el-input>
                            </el-form-item>
                          </el-col>
                          <el-col :span=10 >
                            <el-form-item label="详细地址" prop="addressInfo">
                              <el-input v-model="address.addressInfo"></el-input>
                            </el-form-item>
                          </el-col>
                        </el-row>
                        <el-row :gutter="10">
                          <el-col :span=6 >
                            <el-form-item label="距离" prop="retailStore">
                              <el-select v-model="address.retailStore" placeholder="门店请选择" >
                                <el-option
                                  v-for="item in deptEnum"
                                  :key="item"
                                  :label="item"
                                  :value="item"
                                >
                                </el-option>
                              </el-select>
                            </el-form-item>
                          </el-col>
                          <el-col :span=8 >
                            <el-form-item label="公交站数" prop="distance">
                              <el-input v-model="address.distance" type="Number" min=0 />
                            </el-form-item>
                          </el-col>
                        </el-row>
                        <el-divider></el-divider>
                      </div>
                      <el-button type="primary" @click="updateFormAddAddress(item.content)">添加地址</el-button>
                    </div>
                    <div style="width: 90%;height: 20px;position: relative;margin: 10px;">
                      <el-button type="primary" style="position: absolute;right: 20px;" @click="confirmAddress(item.content)">
                        保 存
                      </el-button>
                    </div>
                  </el-form>
                </div>
                

                </el-tab-pane>
              </el-tabs>

            </el-main>
            <el-aside width="220px">
              <el-menu
                @select="(key, keyPath) => handleMenuSelect(key, keyPath, item.content)" 
                default-active="2"
                :default-openeds="defaultOpen"
                class="el-menu-vertical-demo"
                @open="handleOpen"
                @close="handleClose">
                <el-submenu index="会员管理" >
                  <template slot="title">
                    <span style="font-weight: 600;font-size: 18px;">会员管理</span>
                  </template>
                    <el-menu-item index="会员基础信息查询" style="font-size: 14px">会员基础信息查询</el-menu-item>
                </el-submenu>
                <el-submenu index="诊前处置" >
                  <template slot="title">
                    <span style="font-weight: 600;font-size: 18px;">诊前处置</span>
                  </template>
                    <el-menu-item index="诊前·实验室检查开立" style="font-size: 14px">诊前·实验室检查开立</el-menu-item>
                    <el-menu-item index="诊前·诊室检查开立" style="font-size: 14px">诊前·诊室检查开立</el-menu-item>
                    <el-menu-item index="诊前·信息采集" style="font-size: 14px">诊前·信息采集</el-menu-item>
                </el-submenu>
                <el-submenu index="会员就诊记录查询" >
                  <template slot="title">
                    <span style="font-weight: 600;font-size: 18px;">会员就诊记录查询</span>
                  </template>
                    <el-menu-item index="会员就诊记录查询" style="font-size: 14px">会员就诊记录查询</el-menu-item>
                </el-submenu>
                <el-submenu index="缴费/卡/券" >
                  <template slot="title">
                    <span style="font-weight: 600;font-size: 18px;">缴费/卡/券</span>
                  </template>
                    <el-menu-item index="会员缴费/卡/券记录查询" style="font-size: 14px">会员缴费/卡/券记录查询</el-menu-item>
                </el-submenu>
                <el-submenu index="租借药盒" >
                  <template slot="title">
                    <span style="font-weight: 600;font-size: 18px;">租借药盒</span>
                  </template>
                    <el-menu-item index="会员租借药盒记录查询" style="font-size: 14px">会员租借药盒记录查询</el-menu-item>
                </el-submenu>
              </el-menu>
            </el-aside>
          </el-container>
        </div>

      </el-tab-pane>
    </el-tabs>
  </div>
</template>

<script>

import { getList as getPatientList, add, edit, del, getAllPatientList} from '@/api/patient'
import { addOrEdit } from '@/api/patientAddress'
import { regionData } from 'element-china-area-data'
import { getAllUserList, getListByDept as getUserListByDept, getLoginInfo } from '@/api/user'
import { getList as getSourceList} from '@/api/source'
import { getList, addOrUpdate, guidanceWaitingNumber, stop} from '@/api/guidance'
import { getListByPinyinCode, queryByCodeAnDepositoryId, getListByPinyinCodeProductTime, queryByCodes } from '@/api/drug'
import { queryDepositoryIdsByOptType } from '@/api/drugDepositoryAuth'
import Decimal from 'decimal.js';
import { addDate } from '@/utils/dateUtil'
import { getList as getJobOfficeList} from '@/api/jobOffice'
import { add as addInspection, getInspectionByGuidanceCode} from '@/api/visitInspection'
import { getLastNextVisit } from '@/api/nextVisit'
import { getInfo as getTemplateByJobOfficeId } from '@/api/visitTemplateJobOffice'

export default {
  name: "GuidanceList",
  filters: {
    birthdayTypeFilter(status) {
      const statusMap = ['', '阳', '阴']
      return statusMap[status]
    },
    statusColorFilter(status) {
      const statusMap = ['', '', '', '', '', 'success', 'info']
      return statusMap[status]
    },
    statusFilter(status) {
      const statusMap = ['候诊', '就诊中', '实验室检查', '缴费中', '取药中', '已完成', '中止']
      return statusMap[status]
    }
  },
  data() {
    const validateName = (rule, value, callback) => {
      if (!value) callback(new Error('请输入姓名')) 
      else callback()
    }
    const validatePhone = (rule, value, callback) => {
      if (!value) callback(new Error('请输入电话')) 
      else callback()
    }
    const validateIdCard = (rule, value, callback) => {
      if (!value) callback(new Error('请输入身份证号')) 
      else callback()
    }
    const validateSex = (rule, value, callback) => {
      if (!value) callback(new Error('请选择性别')) 
      else callback()
    }
    const validateBirthday = (rule, value, callback) => {
      if (!value) callback(new Error('请选择出生日期')) 
      else callback()
    }
    const validateBirthdayType = (rule, value, callback) => {
      if (!value) callback(new Error('请选择类型')) 
      else callback()
    }
    const validateSource = (rule, value, callback) => {
      if (!value) callback(new Error('请选择来源')) 
      else callback()
    }
    const validateAddressPre = (rule, value, callback) => {
      var flag = false
      for (const address of this.addPatientForm.addressList) {
        if(!address.addressPre || address.addressPre.length < 3) flag = true
      }
      if (flag) callback(new Error('地址不能为空')) 
      else callback()
    }
    const validateAddressMid = (rule, value, callback) => {
      var flag = false
      for (const address of this.addPatientForm.addressList) {
        if(!address.addressMid || address.addressMid==='') flag = true
      }
      if (flag) callback(new Error('小区不能为空')) 
      else callback()
    }
    const validateAddressInfo = (rule, value, callback) => {
      var flag = false
      for (const address of this.addPatientForm.addressList) {
        if(!address.addressInfo || address.addressInfo === '') flag = true
      }
      if (flag) callback(new Error('地址不能为空')) 
      else callback()
    }
    const validateMultiAddressDes = (rule, value, callback) => {
      var flag = false
      for (const address of this.addPatientForm.addressList) {
        if(!address.multiAddressDes) flag = true
      }
      if (flag) callback(new Error('多址选择不能为空')) 
      else callback()
    }
    const validateMultiAddressDesOther = (rule, value, callback) => {
      var flag = false
      for (const address of this.addPatientForm.addressList) {
        if(address.multiAddressDes == '其他' && (!address.multiAddressDesOther || address.multiAddressDesOther === '')) flag = true
      }
      if (flag) callback(new Error('其他原因不能为空')) 
      else callback()
    }
    const validateRetailStore = (rule, value, callback) => {
      var flag = false
      for (const address of this.addPatientForm.addressList) {
        if(!address.retailStore) flag = true
      }
      if (flag) callback(new Error('门店不能为空')) 
      else callback()
    }
    const validateDistance = (rule, value, callback) => {
      var flag = false
      for (const address of this.addPatientForm.addressList) {
        if(!address.distance && address.distance == '') flag = true
      }
      if (flag) callback(new Error('公交站数不能为空')) 
      else callback()
    }
    return {
      list: [],
      listLoading: true,
      patientList: null,
      patientListLoading: true,
      currentPage: 1,
      pageSize: 10,
      total: 0,
      curIndex: -1,
      infoVisible: false,
      addPatientformVisible: false,
      info: {},
      addPatientForm: {},
      query: {},
      dialogTitle: '添加来源',
      depts:[],
      editableTabsValue: '挂号列表',
      editableTabs: [],
      patientTabsValue: '',
      patientTabs: [],
      sourceEnum: [],
      sexEnum: ["男", "女"],
      userEnum: [],
      doctorEnum: [],
      patientEnum: [],
      jobOfficeEnumAll: [],
      jobOfficeEnum: [],
      workAddressEnum: [],
      waitTimeEnum: ['5', '10', '15', '20', '30', '60', '120'],
      typeEnum: [{id: 1, name: '店面就诊'},{id: 2, name: '邮寄'},{id: 3, name: '代取'},{id: 4, name: '代放'}],
      options: regionData,
      birthdayTypeEnum:[{id: 1, name: '公历'}, {id: 2, name: '农历'}],
      multiAddressDesEnum: ["临时居住", "子女居所", "邮寄用地址", "其他"],
      deptEnum: ['劳动店', '永春店'],
      introducerDisable: true,
      defaultOpen: ['会员管理', '诊前处置', '会员就诊记录查询', '缴费/卡/券', '租借药盒'],
      addPatientFormRules: {
        name: [{ required: true, trigger: 'blur', validator: validateName }],
        phone: [{ required: true, trigger: 'blur', validator: validatePhone }],
        idCard: [{ required: true, trigger: 'blur', validator: validateIdCard }],
        sex: [{ required: true, trigger: 'blur', validator: validateSex }],
        birthday: [{ required: true, trigger: 'blur', validator: validateBirthday }],
        birthdayType: [{ required: true, trigger: 'blur', validator: validateBirthdayType }],
        source: [{ required: true, trigger: 'blur', validator: validateSource }],
        addressPre: [{ required: true, trigger: 'blur', validator: validateAddressPre }],
        addressMid: [{ required: true, trigger: 'blur', validator: validateAddressMid }],
        addressInfo: [{ required: true, trigger: 'blur', validator: validateAddressInfo }],
        multiAddressDes: [{ required: true, trigger: 'blur', validator: validateMultiAddressDes }],
        multiAddressDesOther: [{ required: true, trigger: 'blur', validator: validateMultiAddressDesOther }],
        retailStore: [{ required: true, trigger: 'blur', validator: validateRetailStore }],
        distance: [{ required: true, trigger: 'blur', validator: validateDistance }],
      },
      noMasterDoctorNum: 0,
      noInfoNum: 0,
      noCheckNum: 0,
      noInspectionNum: 0,
      doneWaitingNum: 0,
      guidanceTitleEnum: ['诊前·实验室检查开立', '诊前·诊室检查开立' , '诊前·信息采集']
    }
  },
  created() {
    this.fetchData()
    this.startInterval();
  },  
  beforeDestroy() {
    this.stopInterval();
  },
  methods: {
    fetchData() {
      this.listLoading = true
      this.initListData()

      getSourceList().then(sourceRes=>{
        this.sourceEnum = sourceRes.data
      })
      getAllPatientList().then(res=>{
        console.log("patient res:", res)
        this.patientEnum = res.data
      })
      getAllUserList().then(res=>{
        console.log("user res:", res)
        this.userEnum = res.data
      })
    },
    clickCurPage(val){
      this.currentPage = val
      this.fetchData()
    },
    initListData() {
      var loginInfo = this.$store.getters.userInfo.loginInfo
      var deptId = loginInfo.loginDept.deptId
      // var workAddressId = loginInfo.loginWorkAddress.id
      var jobOfficeId = loginInfo.loginJobOffice?loginInfo.loginJobOffice.jobOfficeId:undefined
      this.$set(this, 'listLoading', true)
      getList({currentPage: this.currentPage, pageSize: this.pageSize, deptId: deptId, jobOfficeId: jobOfficeId}).then(res=>{
        console.log(res.data)
        this.list = res.data.records
        this.noMasterDoctorNum = this.list.filter(item=> !item.doctorId).length
        this.doneWaitingNum = this.list.filter(item=> item.remainderTime == 0).length
        this.noInspectionNum = this.list.filter(item=> !item.masterDoctor).length
        this.noCheckNum = this.list.filter(item=> !item.masterDoctor).length
        this.noInfoNum = this.list.filter(item=> !item.masterDoctor).length
        this.listLoading = false
      }).catch(err=>{
        console.log("err")
        console.log(err)
        this.listLoading = false
      })
      guidanceWaitingNumber({deptId: deptId, workAddressId: undefined, jobOfficeId: jobOfficeId}).then(res=> {
        this.reports = res.data
      })
    },
    getInfo(row) {
      this.info = row
      this.infoVisible = true
    },
    update(row) {
      this.reset()
      this.dialogTitle = '修改来源'
      this.form = JSON.parse(JSON.stringify(row))
      this.formVisible = true
    },
    tableRowClassName({row, rowIndex}) {
      if (row.status === 0 && row.remainderTime === 0) {
        return 'warning-row';
      } else if (row.status != 0) {
        return 'done-row';
      }
      return '';
    },
    cancel() {
      this.formVisible = false
    },
    reset(){
      this.form = {}
    },
    removeTab(targetName) {
      let tabs = this.editableTabs;
      let activeName = this.editableTabsValue;
      if (activeName === targetName) {
        tabs.forEach((tab, index) => {
          if (tab.name === targetName) {
            let nextTab = tabs[index + 1] || tabs[index - 1];
            if (nextTab) {
              activeName = nextTab.name;
            }
          }
        });
      }
      
      this.editableTabsValue = activeName;
      this.editableTabs = tabs.filter(tab => tab.name !== targetName);
    },
    removePatientTab(targetName, patient) {
      let tabs = patient.patientTabs;
      let activeName = patient.patientTabsValue;
      if (activeName === targetName) {
        tabs.forEach((tab, index) => {
          if (tab.name === targetName) {
            let nextTab = tabs[index + 1] || tabs[index - 1];
            if (nextTab) {
              activeName = nextTab.name;
            }
          }
        });
      }
      patient.patientTabsValue = activeName;
      patient.patientTabs = tabs.filter(tab => tab.name !== targetName);
    },
    search() {
      this.getPatientList({name: this.query.name})
    },    
    resetForm(formName) {
      this.$refs[formName].resetFields();
    },
    //  get patient list page function
    getPatientList(params) {
      this.patientListLoading = true
      params.currentPage = this.currentPage
      params.pageSize = this.pageSize 
      getPatientList(params).then(res=>{
        this.patientList = res.data.records
        console.log(this.patientList)
        this.patientList.forEach(item=>{
          item.age = new Date().getFullYear() - item.birthday.substring(0,4)
          item.addressList.forEach(address=>{
            var addressPreArr = address.address.split('|||')
            address.addressPre = [addressPreArr[0], addressPreArr[1], addressPreArr[2]]
            this.$set(address, 'addressMid', addressPreArr[3])
            this.$set(address, 'addressInfo', addressPreArr[4])
          })
        })
        this.patientListLoading = false
      }).catch(err=>{
        console.log("err")
        console.log(err)
        this.patientListLoading = false
      })
      
    },
   
    handleChange (address) {
      this.$set(this.addPatientForm, 'addressPre', address)
    },
    addAddress() {
      this.addPatientForm.addressList.push({})
    },
    deleteAddress(address, list) {
      list.splice(list.indexOf(address), 1);
    },
    updateFormAddAddress(updateForm) {
      updateForm.addressList.push({})
    },
    changeBirthday() {

    },
    changeMultiAddressDes(item, address) {
      if(item == '其他')  {
        this.$set(address, 'isOtherAddress', 1)
      } else {
        this.$set(address, 'isOtherAddress', 0)
      }
    },
    confirm() {
      this.$refs.addPatientForm[0].validate(valid => {
        if (valid) {
          console.log(this.addPatientForm)
          this.addPatientForm.addressList.forEach(address=>{
            address.address = address.addressPre[0] + ' ' + address.addressPre[1] + ' ' + address.addressPre[2] + ' ' + address.addressMid + ' ' + address.addressInfo
          })
          add(this.addPatientForm).then(res=>{
            console.log(res)
            this.$message({
              message: '添加成功',
              type: 'success'
            })
            this.editableTabsValue = "1"
          }).catch(err=>{
            console.log(err)
          })
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    updateConfirm(updateForm) {
      // this.$refs.updatePatientForm[0].validate(valid => {
      //   if (valid) {
          console.log(updateForm)
          updateForm.addressList.forEach(address=>{
            address.address = address.addressPre[0] + ' ' + address.addressPre[1] + ' ' + address.addressPre[2] + ' ' + address.addressMid + ' ' + address.addressInfo
          })
          edit(updateForm).then(res=>{
            console.log(res)
            this.$message({
              message: '修改成功',
              type: 'success'
            })
            this.editableTabsValue = "1"
          }).catch(err=>{
            console.log(err)
          })
        // } else {
        //   console.log('error submit!!')
        //   return false
        // }
      // })
    },

    initPatientVisitData(patient, list) {
      console.log("patient:",patient)
      if(list.length != 0) {
        this.editableTabsValue = patient.code
        return
      }
      var loginDept = this.$store.getters.userInfo.loginInfo.loginDept
      getUserListByDept(loginDept.deptId).then(res=>{
        console.log("res", res)
        this.doctorEnum = res.data
      })
      getJobOfficeList().then(res=>{
        this.jobOfficeEnumAll = res.data
      })
      this.$set(patient, 'patientTabsValue', '诊前处置')
      this.$set(patient, 'patientTabs', [{
        title: '诊前处置',
        name: '诊前处置',
        content: {}
      }])
      this.$set(patient, 'visitActiveName', '')
      this.$set(patient, 'visitInspectionRealReport', [{guidanceCode: patient.guidanceInfo.guidanceCode, PLAN_AMOUNT: '处方金额', CARD_PLAN_AMOUNT: '储值卡处方金额', ACTIVITY_PLAN_AMOUNT: '活动处方金额', ACTIVITY_CARD_PLAN_AMOUNT: '活动+储值卡金额'}])
      this.$set(patient, 'visitInspectionList', [])
      this.$set(patient, 'visitCheckList', [])
      // 检查列表
      this.initInspectionList(patient)
      // 诊室检查模板
      this.initCheckTemplate(patient)

      this.editableTabs.push({
        title: patient.name,
        name: patient.code,
        content: patient
      })
      this.editableTabsValue = patient.code
    },
    initCheckTemplate(patient) {
      var jobOfficeId = patient.guidanceInfo.jobOfficeId
      getTemplateByJobOfficeId({jobOfficeId: jobOfficeId}).then(res=> {
        console.log("checkTemplate", res)
        patient.checkTemplateEnum = res.data
        var tmpCheckTemplate = res.data.filter((item, index, self) => self.findIndex((other) => other['templateCode'] === item['templateCode']) === index);
        this.$set(patient, 'checkTemplate', tmpCheckTemplate)
        patient.checkTemplate.forEach(checkTemplate=> {
          var templateContent = patient.checkTemplateEnum.filter(item=>item.templateCode == checkTemplate.templateCode)
          templateContent.forEach(item=> {this.$set(item, 'value', '')})
          this.$set(checkTemplate, 'templateContent', templateContent)
        })
        // patient.checkTemplate.forEach(item => {
        //   item.templateName = item.templateName + '\n这啥'
        // })
      })
    },
    initInspectionList(patient) {
      getInspectionByGuidanceCode({guidanceCode: patient.guidanceInfo.guidanceCode}).then(inspectionInfoRes=> {
        console.log("get inspectionRes",inspectionInfoRes.data)
        // 如果已开检查 加载已开
        if(inspectionInfoRes.data && inspectionInfoRes.data.length != 0) {
          inspectionInfoRes.data.forEach(item=> {
            item.operation = Number(item.operation)
            patient.visitInspectionList.push(item)
          })
          this.inputRealQuantity(patient)
        } else {  // 如果没开检查 加载上次预案
          getLastNextVisit({userId: patient.id}).then(res=> {
            if(res.data) {
              var nextVisitDailyList = JSON.parse(res.data.nextVisitDailyList)
              var nextVisitList = JSON.parse(res.data.nextVisitList)
              var drugEnum = []
              if(nextVisitDailyList && nextVisitDailyList.length != 0) {
                var query = {drugCodes: nextVisitDailyList.map(obj=> obj.code).join(',')}
                queryByCodes(query).then(drugRes=> {
                  drugEnum.push(...drugRes.data)
                  nextVisitDailyList.forEach(dailyInspection => {
                    var drug = drugEnum.filter(drug=> drug.code == dailyInspection.code)[0]
                    drug.realQuantity = 1
                    drug.source = '日常检查'
                    drug.id = undefined
                    drug.status = 0
                    patient.visitInspectionList.push(JSON.parse(JSON.stringify(drug)))
                    this.inputRealQuantity(patient)
                  })
                  if(nextVisitList && nextVisitList.length != 0) {
                    queryByCodes({drugCodes: nextVisitList.map(obj=> obj.code).join(',')}).then(drugRes=> {
                      drugEnum.push(...drugRes.data)
                      nextVisitList.forEach(dailyInspection => {
                        var drug = drugEnum.filter(drug=> drug.code == dailyInspection.code)[0]
                        drug.realQuantity = 1
                        drug.source = '医嘱检查'
                        drug.id = undefined
                        drug.status = 0
                        patient.visitInspectionList.push(JSON.parse(JSON.stringify(drug)))
                        this.inputRealQuantity(patient)
                      })
                    })
                  }
                })
              } else {
                if(nextVisitList && nextVisitList.length != 0) {
                  queryByCodes({drugCodeList: nextVisitList}).then(drugRes=> {
                    drugEnum.push(...drugRes.data)
                    nextVisitList.forEach(dailyInspection => {
                      var drug = drugEnum.filter(drug=> drug.code == dailyInspection.code)[0]
                      drug.realQuantity = 1
                      drug.source = '医嘱检查'
                      drug.id = undefined
                      drug.status = 0
                      patient.visitInspectionList.push(JSON.parse(JSON.stringify(drug)))
                      this.inputRealQuantity(patient)
                    })
                  })
                }
              }
            }
          })
        }
      })
      
    },

    /** patient detail page function */
    handleOpen(key, keyPath) {
      console.log(key, keyPath);
    },
    handleClose(key, keyPath) {
      console.log(key, keyPath);
    },
    handleMenuSelect(key, keyPath, patient) {
      console.log(patient)
      var tabValue = keyPath[0]
      console.log(tabValue)
      this.$set(patient, 'visitActiveName', keyPath[1])
      var list = patient.patientTabs.filter(item => item.name == tabValue)
      if(list.length != 0) {
        patient.patientTabsValue = tabValue
        return
      }

      patient.patientTabs.push({
        title: tabValue,
        name: tabValue,
        content: {}
      })
      patient.patientTabsValue = tabValue
    },
    guidanceFormConfirm() {
      console.log('提交')
    },
    optionGuidance(visit) {
      getPatientList({name: visit.patientCode, currentPage: 1, pageSize: 1}).then(res=> {
        var patient = res.data.records[0]
        patient.guidanceInfo = visit
        var list = this.editableTabs.filter(item => item.name == patient.code)
        this.initPatientVisitData(patient, list)
      })
    },
    queryInspectionSearch(queryString, cb) {
      queryDepositoryIdsByOptType({optType: 2}).then(res=> {
        if(res.data.length == 0) {
          this.$message.error('无销售权限')
          cb([{name: '无销售权限'}])
          return
        }
        getListByPinyinCodeProductTime(queryString, res.data, 1).then(drugListRes=>{
          console.log("drugListRes", drugListRes)
          // 调用 callback 返回建议列表的数据
          cb(drugListRes.data);
        })
      })
    },
    handleInspectionSelect(item, index, patient) {
      if(!item.code) return
      item.drugCode = item.code
      item.source = "添加"
      this.$set(item, 'realQuantity', 1)
      this.$set(patient, 'InspectionSearchValue', '')
      item.id = undefined
      item.status = 0
      item.guidanceCode = patient.guidanceInfo.guidanceCode
      this.$set(item, 'totalPrice1', item.realQuantity ? Decimal(item.realQuantity).mul(item.unitPrice) : 0)
      this.$set(item, 'totalPrice2', item.realQuantity ? Decimal(item.realQuantity).mul(item.unitPrice) : 0)
      patient.visitInspectionList.push(item)
      this.inputRealQuantity(patient)
    },
    callApi() {
      // 调用接口的逻辑
      console.log('刷新诊前列表');
      this.initListData()
    },
    startInterval() {
      this.intervalId = setInterval(this.callApi, 1000 * 60);
    },
    stopInterval() {
      if (this.intervalId) {
        clearInterval(this.intervalId);
      }
    },
    selectoperation(radioValue, inspection) {
      if(radioValue == 2) {
        this.$prompt('请输入不操作原因', '不操作', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          inputPattern: /\S/,
          inputErrorMessage: '原因不能为空'
        }).then(({ value }) => {
          this.$set(inspection, 'operation', radioValue)
          this.$set(inspection, 'operationMark', value)
        }).catch((e) => {
          console.log(e)
        });
      } else {
        this.$set(inspection, 'operation', radioValue)
      }
      // source
      if(radioValue == 3) {
        if(inspection.source == '添加') this.$set(inspection, 'source', '预存')
        else inspection.source += '\n 预存'
      } else {
        inspection.source = inspection.source.split('\n').join('').split('预存').join('')
      }
    },
    confirmVisit(patient, type) {
      console.log(patient)
      if(type == 1) {
        var addInspectionReqDto = {
          guidanceCode: patient.guidanceInfo.guidanceCode,
          visitInspectionList: patient.visitInspectionList,
          visitInspectionRealReportList: patient.visitInspectionRealReport
        }
        addInspection(addInspectionReqDto).then(res=> {
          console.log(res)
          this.$set(patient, 'visitActiveName', this.guidanceTitleEnum[type])
        })
      } else if (type == 2) {

        this.$set(patient, 'visitActiveName', this.guidanceTitleEnum[type])
      } else if (type == 3) {
        
        this.$set(patient, 'visitActiveName', undefined)
      }
    },
    stopVisit(patient) {
      this.$prompt('请输入停止服务原因', '停止服务', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        inputPattern: /\S/,
        inputErrorMessage: '原因不能为空'
      }).then(({ value }) => {
        patient.isStop = 1
        patient.stopRemarks = value
        var query = {
          guidanceCode: patient.guidanceInfo.guidanceCode,
          stop: 1,
          stopRemarks: patient.stopRemarks
        }
        stop(query).then(res=> {
          console.log(res)
        })
      }).catch((e) => {
        console.log(e)
      });
    },
    inputRealQuantity(patient, item) {
      var reportObj = patient.visitInspectionRealReport[0]
      var sum = patient.visitInspectionList.reduce((sum, inspection) => sum + Number(Decimal(inspection.realQuantity).mul(Decimal(inspection.unitPrice))), 0)
      this.$set(reportObj, 'planAmount', Decimal(sum).toFixed(1, Decimal.ROUND_HALF_UP))
      if(patient.visitInspectionList && patient.visitInspectionList.length != 0) {
        patient.visitInspectionList.forEach(item => {
          this.$set(item, 'totalPrice1', item.realQuantity ? Decimal(item.realQuantity).mul(item.unitPrice) : 0)
          this.$set(item, 'totalPrice2', item.realQuantity ? Decimal(item.realQuantity).mul(item.unitPrice) : 0)
        })
      }
    },

  }
}
</script>


<style>
  .el-aside {
    width: 20%;
    text-align: center;
  }
  
  .el-main {
    width: 80%;
    text-align: left;
  }
  
  body > .el-container {
    margin-bottom: 40px;
  }
  .main-head-title {
    font-size: 14px;
  }
  .el-table .cell {
    white-space: pre-line;
  }

  .item {
    margin-top: 10px;
  }
  
</style>